<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Search, Calendar, User, House } from '@element-plus/icons-vue'
import router from '@/router'
import path from 'path'
import { useRoute } from 'vue-router'
import { userStore } from '@/stores/userStoret.js';
import {logout} from '../api/users.js'
import {getHotHotel} from '@/api/hotel.js';
import {getRecommendHotel} from '@/api/hotel.js';
import dayjs from 'dayjs'

// 搜索表单数据
const searchForm = ref({
  keyword: '', // 酒店地址或名称
  checkInDate: '', // 入住时间
  checkOutDate: '', // 退房时间
  roomCount: 1, // 预定房间数
  guestCount: 2, // 入住人数
  otherKeywords: '' // 其他关键词
})

const route = useRoute()

const recommendHotelList =  ref([])

// 点击搜索
const searchKeyword = ref('')

// 点击搜索
const handleSearch1 = () => {
  if (!searchKeyword.value) return
  router.push({
    path: '/hotelSearchList',
    query: { keyword: searchKeyword.value } // 传递关键字到搜索列表页
  })
}


// 搜索
const handleSearch = () => {
  const checkIn = searchForm.value.checkInDate
    ? dayjs(searchForm.value.checkInDate).format('YYYY-MM-DD')
    : '';
  const checkOut = searchForm.value.checkOutDate
    ? dayjs(searchForm.value.checkOutDate).format('YYYY-MM-DD')
    : '';

  router.push({
    path: '/hotelSearchList',
    query: {
      keyword: searchForm.value.keyword || '',
      checkInDate: checkIn,
      checkOutDate: checkOut,
      roomCount: searchForm.value.roomCount || 1,
    },
  });

  console.log('搜索参数:', {
    keyword: searchForm.value.keyword,
    checkInDate: checkIn,
    checkOutDate: checkOut,
    roomCount: searchForm.value.roomCount,
  });
};

//点击登录跳转登录页面
function toLogin(){
  router.push(`/login`)
}
function test(){
  router.push(`/login`)
}
//点击我的跳转到我的页面
// function toMy(){
//   router.push(`/my`)
// }
function toMy() {
  const isLogged =
    userStore.logged ||
    (localStorage.getItem("token") && localStorage.getItem("userId"));

  if (!isLogged) {
    // 未登录，跳转到登录页
    router.push("/login");
  } else {
    // 已登录，跳转到“我的”页面
    router.push("/my");
  }
}

//点击跳转酒店详情页面
function tohDetail(hotelId) {
  router.push(`/hDetail/${hotelId}`)
}
const logged = computed(()=>userStore.logged)
const userName = computed(()=>userStore.userName)
const userId = computed(()=>userStore.userId)
const token = computed(()=>userStore.token)

/**
 * 页面加载的时候，
 *  获得localStorage中的token,userName  
 * 1. localStorage 有数据
 * 2. localStorage 没有数据 
 */
onMounted(()=>{
  const utoken = localStorage.getItem("token")
  const uid = localStorage.getItem("userId")
  const uname = localStorage.getItem("userName")

  if(utoken&&uid&&uname){
    userStore.logged = true
    userStore.userId = uid
    userStore.userName = uname
    userStore.token = utoken
    console.log("恢复用户信息：", userStore);
   
    console.log("onMounted userId = " + userStore.userId)
    console.log("onMounted userName = " + userStore.userName )
    console.log("onMounted token = " + userStore.token )
    console.log("onMounted logged = " + userStore.logged)
    //登录状态 -> 调用推荐接口
    getRecommendHotels(uid);
  }else{
    //未登录 -> 调用热门酒店
     getHotHotels();
     }
})
  //  获得用户详细信息
  // async function getUserDetailInfo(){
  //   if(! userStore.userId) return 
  //   const response = await getUserInfo(userStore.token);
  //     console.log("登录用户详情-----：", );
  //     console.log(response.data.data) 
  // }


  //退出
 async function userLogout(){     
    try {
       if (userStore.userId) {
          await logout(userStore.userId);
       console.log("用户 " + userStore.userId + " 已退出");
      }
    } catch (e) {
      console.log("退出请求失败", e);
    } finally {
        localStorage.removeItem("userId");
        localStorage.removeItem("token");
        localStorage.removeItem("userName");
        userStore.token = "";
        userStore.userId = "";
        userStore.userName = "";
        userStore.logged = false;
        router.push("/"); //退出后跳回首页
    }
  }
  //热数据缓存
  async function getHotHotels(){
     const response = await getHotHotel()
     console.log(response)
     recommendHotelList.value = response.data.data
     console.log(recommendHotelList.value)  
  }
  //推荐引擎
  async function getRecommendHotels(userId){
    try{
    const response = await getRecommendHotel(userId);
    console.log("推荐酒店",response.data);
    recommendHotelList.value = response.data.data || [];
  }catch(err){
    console.error("推荐酒店获取失败:",err);
    recommendHotelList.value = [];
  }
}

</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="logo-section">
            <img src="/images/logo.png" alt="logo" width="140px"/>
          </div>
            <!-- 头部搜索框 -->
            <div class="header-search-section">
              <el-input 
                v-model="searchKeyword"
                placeholder="搜索酒店、城市..."
                clearable
                size="large"
              >
              </el-input>
              <el-button 
                class="header-search-button" 
                type="primary" 
                size="large"
                @click="handleSearch1"
              >
                搜索
              </el-button>
            </div>
            <div class="nav-section">
            <!-- 未登录状态 -->
            <el-button
              type="primary"
              v-if="!userName"
              plain
              @click="toLogin()"
            >
              登录
            </el-button>
            
            <!-- 已登录状态 -->
            <template v-else>
              <el-button
                type="success"
                class="user-btn"
              >
                {{ userName }}
              </el-button>
               <el-button
                  type="primary"
                  plain
                  @click="userLogout()"
                >
                  退出
                </el-button>
            </template>

            <el-button
              type="primary"
              plain
              @click="toMy()"
            >
              我的
            </el-button>
          </div>

        </div>
      </el-header>
        
      <el-main class="main-content">
        <div class="search-container">
          <div class="search-title">
          </div>
          
          <el-form :model="searchForm" class="search-form" label-width="100px">
            <!-- 酒店地址或名称搜索 -->
            <div class="form-row">
              <el-form-item label="关于酒店" class="form-item">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入酒店地址或名称"
                  clearable
                  size="large"
                >
                </el-input>
              </el-form-item>
            </div>

            <!-- 入住退房时间 -->
            <div class="form-row">
              <el-form-item label="入住时间" class="form-item">
                <el-date-picker
                  v-model="searchForm.checkInDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择入住日期"
                  size="large"
                  class="date-picker"
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-date-picker>
              </el-form-item>
              
              <el-form-item label="退房时间" class="form-item">
                <el-date-picker
                  v-model="searchForm.checkOutDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择退房日期"
                  size="large"
                  class="date-picker"
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-date-picker>
              </el-form-item>
            </div>

            <!-- 房间数和入住人数 -->
            <div class="form-row">
              <el-form-item label="房间数" class="form-item">
                <el-input-number
                  v-model="searchForm.roomCount"
                  :min="1"
                  :max="10"
                  size="large"
                >
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="入住人数" class="form-item">
                <el-input-number
                  v-model="searchForm.guestCount"
                  :min="1"
                  :max="20"
                  size="large"
                >
                </el-input-number>
              </el-form-item>
            </div>



            <!-- 搜索按钮 -->
            <div class="search-button-container">
              <el-button 
                type="primary" 
                size="large" 
                @click="handleSearch"
            
              >
              <!-- class="search-button" -->
                搜索酒店
              </el-button>
            </div>
          </el-form>
        </div>
        
          <div class="recommend">
            <h2>热门酒店推荐</h2>
            <ul >
              <li @click="tohDetail(hotel.hotelId)" v-for="hotel in recommendHotelList" :key="hotel.hotelId">
                <img :src="`${hotel.hotelImage}`" :alt="hotel.name">
                <div class="recommend_name">{{hotel.hotelName}}</div>
                <div class="recommend_score">{{hotel.hotelRating}}</div>
                <div class="recommend_price">￥{{ hotel.minRoomPrice}}</div>
              </li>
            </ul>
          </div>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
/* recommend 酒店推荐样式 */
.recommend  {
  width: 90%;
  height: 500px;
  /* background-color: #764ba2; */
  margin-top: 100px;
}
.recommend ul{
  list-style: none;
}
.recommend ul li{
  width: 250px;
  height: 300px;
  float: left;
  margin-left: 40px;
  margin-top: 40px;
  /* background-color: #c3cfe2; */
  background-color: #fafafa;
  border-radius: 10px;
}
.recommend ul li div{
  margin-top: 7px;
  padding-left: 8px;
}
.recommend img{
  width: 100%;
    border-radius: 10px 10px 0 0;
}
.recommend_name{
  color: #333;
  font-size: 22px;
  font-weight: bold;
}
.recommend_score{
  display: inline-block;
  margin-left: 8px;
  padding-right: 8px;
  padding-top: 3px;
  padding-bottom: 3px;
  background: #0086f6;
  border-radius: 4px;
  font-size: 16px;
  color: #333;
}
.recommend_price{
  color: #0086f6 ;
  font-weight: bold;
  font-size: 20px;
}
.nav-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 已登录状态的用户名按钮 */
.user-btn {
  width: 50px;            /* 设定圆的大小 */
  height: 50px;
  border-radius: 50%;     /* 关键：让按钮变圆 */
  padding: 0;             /* 移除默认 padding */
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 14px;
  text-transform: uppercase;
}

/* 悬停时轻微放大 */
.user-btn:hover {
  transform: scale(1.05);
}


/* Header 样式 */
.header {
  width: 100%;
  height: 130px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-content {
  width: 100%;
  max-width: 1200px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.logo-section {
  display: flex;
  align-items: center;
}

.header-search-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  max-width: 500px;
  margin: 0 30px;
}

.header-search-button {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.5);
  color: white;
  border-radius: 25px;
  padding: 12px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.header-search-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.8);
  /* transform: translateY(-1px); */
}

.nav-section {
  display: flex;
  gap: 12px;
}

.nav-section .el-button {
  color: white;
  border-color: rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.nav-section .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
}

/* Main 内容样式 */
.main-content {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 80px);
  padding: 40px 20px;
  display: flex;
  flex-direction: column; 
  justify-content: flex-start;
  align-items: center;  
}

.search-container {
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 800px;
  margin-top: 20px;

}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
  margin-bottom: 0;
}

.form-item :deep(.el-form-item__label) {
  color: #2c3e50;
  font-weight: 500;
  font-size: 14px;
}

.date-picker {
  width: 100%;
}

.date-picker :deep(.el-input__inner) {
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  padding: 12px 15px 12px 40px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.date-picker :deep(.el-input__inner):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 搜索按钮样式 */
.search-button-container {
  text-align: center;
  margin-top: 30px;
}

.search-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 25px;
  padding: 15px 40px;
  font-size: 16px;
  font-weight: 600;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.search-button:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    padding: 0 15px;
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .header-search-section {
    order: 3;
    width: 100%;
    max-width: none;
    margin: 0;
  }
  
  .nav-section {
    gap: 8px;
  }
  
  .nav-section .el-button {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .header-search-button {
    padding: 10px 15px;
    font-size: 13px;
  }
  
  .search-container {
    padding: 30px 20px;
    margin: 10px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .form-item {
    min-width: 100%;
  }
}

@media (max-width: 480px) {
  .header {
    height: 70px;
  }
  
  .logo-section img {
    width: 120px;
  }
  
  .nav-section .el-button {
    padding: 6px 10px;
    font-size: 11px;
  }
  
  .search-container {
    padding: 20px 15px;
  }
}
</style>
